package webSocket.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import util.constant.Constant;
import webSocket.init.WebsocketChannelInitializer;

public class WebsocketServer implements Runnable{
	
	private final Integer port = Constant.NETTY_CONFIG.PORT;
	private EventLoopGroup parentGroup = new NioEventLoopGroup();
	private EventLoopGroup childGroup = new NioEventLoopGroup();
	


	@Override
	public void run() {
		
		start();
	}
	
	public void start() {
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(parentGroup, childGroup);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.SO_BACKLOG, 128)
					 .option(ChannelOption.SO_KEEPALIVE, true);
			
			bootstrap.childHandler(new WebsocketChannelInitializer());
			
			ChannelFuture channelFuture = bootstrap.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			parentGroup.shutdownGracefully();
			childGroup.shutdownGracefully();
		}
	}
	
}
